package cn.java89.userconsumer.web;

import cn.java89.entity.AjaxResult;
import cn.java89.entity.Page;
import cn.java89.entity.Student;
import cn.java89.service.IStudentService;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("stu")
public class StudentController {
    @Autowired
    private IStudentService studentService;

    @GetMapping("/get/{id}")

    @CircuitBreaker(name = "backendA", fallbackMethod = "getError")
    @TimeLimiter(name = "backendA", fallbackMethod = "getError")
    public AjaxResult get(@PathVariable long id) {
        return studentService.get(id);

    }

    public AjaxResult getError(Throwable t) {
        return AjaxResult.error(505, "服务器繁忙，请稍后再试");
    }

    @PostMapping("/login") //{"phone":"xxx","pass":"fff"}
    public AjaxResult login(String phone, String pass) {
        return studentService.login(phone, pass);
    }

    @GetMapping("/search")
    public Page<Student> search(int pageNo,
                                int pageSize,
                                @RequestParam(required = false) String sname,
                                @RequestParam(required = false) String qq,
                                @RequestParam(required = false) String phone,
                                @RequestParam(required = false) Date enterStart,
                                @RequestParam(required = false) Date enterEnd) {
        return studentService.search(pageNo, pageSize, sname, qq, phone, enterStart, enterEnd);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        //所有的Date类型用一种格式
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        //binder.registerCustomEditor(Date.class,"birthday", new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd
        // hh:mm"), true));
    }
}
